var mongoose = require('mongoose');

var date = new Date();

var UserSchema = new mongoose.Schema({
	username:String,
	email:String,
	password:String,
	register_ip:String,
	register_time:{
		type:Number,
		default:date.getTime()
	},
	last_login_ip:String,
	last_login_time:{
		type:Number,
		default:date.getTime()
	}
});

UserSchema.pre('save',function(next){
	if(this.isNew){
		this.register_time = this.last_login_time  = date.getTime();
	}else{
		this.last_login_time = date.getTime();
	}

	next();
});

UserSchema.statics = {
	fetch:function(cb){
		return this.find({}).sort('register_time');
		exec(cb);
	},

	findById:function(id,cb){
		return this.findOne({_id:id});
		exec(cb);
	}
};

module.exports = UserSchema;